package UDP;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class EchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    // 初始化服务器的 ip 和 服务器的端⼝.
    public EchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        // 这个 new 操作, 就不再指定端⼝了. 让系统⾃动分配⼀个空闲端⼝.
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);

        System.out.println("客户端启动！");
        while(true) {
            //一、从控制台读取用户输入的内容
            System.out.print("> ");
            String request = scanner.next();

            //二、构造成 UDP 请求，并发送，不光要填内容, 还要填服务器的地址和端口.
            DatagramPacket reqPacket = new DatagramPacket(
                    request.getBytes(),
                    request.getBytes().length,
                    //要发送的服务器的 ip 和 端口
                    InetAddress.getByName(serverIp),
                    serverPort);
            socket.send(reqPacket);

            //三、读取服务器的响应。
            DatagramPacket respPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(respPacket);
            String response = new String(respPacket.getData(), 0, respPacket.getLength());

            //把响应显示到控制台。
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient echoClient = new EchoClient("127.0.0.1",9090);
        echoClient.start();
    }
}
